package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.CounterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description:
 */
@Service("SingleCounter")
@Slf4j
public class SingleCounterServiceImpl implements CounterService {

    final String COUNTER_KEY_NAME = "simple::counter";
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean init(int value) {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        //SET
        valueOperations.set(COUNTER_KEY_NAME, value + "");
        log.info("set:{}", value);
        return true;
    }

    @Override
    public long increase() {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        //INCR
        Long increment = valueOperations.increment(COUNTER_KEY_NAME);
        return increment;
    }

    @Override
    public long increase(int num) {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        //INCRBY
        Long increment = valueOperations.increment(COUNTER_KEY_NAME, num);
        return increment;
    }

    @Override
    public long decrease() {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        Long decrement = valueOperations.decrement(COUNTER_KEY_NAME);
        return decrement;
    }

    @Override
    public long decrease(int num) {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        Long decrement = valueOperations.decrement(COUNTER_KEY_NAME, num);
        return decrement;
    }
}
